﻿// ----------------------------------------------------------------------------
//  Copyright (C) 成都联宇创新科技有限公司 版权所有。 
//      
//  文件名：QuartzService.cs
//  文件功能描述：
//  创建标识：骆智慧 2016/03/03 00:00
//     
//  修改标识：骆智慧  2016/03/10/06:40
//  修改描述：
//  ----------------------------------------------------------------------------

#region 导入名称空间

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using Common.Logging;
using Quartz;
using Quartz.Impl;

#endregion

namespace LightWork.Services
{
    /// <summary>
    /// 任务调度模块
    /// </summary>
    [Serializable]
    public class QuartzService : HostedService
    {
        private readonly ILog _log = LogManager.GetLogger<QuartzService>();
        private IScheduler _scheduler;

        /// <summary>
        /// 等待作业完成
        /// </summary>
        public bool WaitJobsComplete { get; set; }

        /// <summary>
        /// Quartz初始化数据
        /// </summary>
        public Dictionary<string, string> QuartzEngineConfig { get; set; }

        #region 重写 用户自定义服务 部分方法

        public override void Initialize()
        {
            if (_scheduler != null) return;

            #region 初始化 Quartz 调度程序

            StartIndex = 1;
            StopIndex = 0;
            ServiceName = "Quartz作业调度";
            try
            {
                var nvc = new NameValueCollection();
                foreach (var item in QuartzEngineConfig)
                    nvc.Add(item.Key, item.Value);

                var schedulerFactory = new StdSchedulerFactory(nvc);
                _scheduler = schedulerFactory.GetScheduler();
            }
            catch (Exception e)
            {
                _log.Error($"装配 Quartz 调度程序失败:{e.Message}");
                throw;
            }

            #endregion
        }

        public override bool Start()
        {
            try
            {
                Initialize();
                if (!_scheduler.IsStarted)
                {
                    _scheduler.Start();
                    CurrentState = CustomerServiceState.Started;
                }

                return true;
            }
            catch (Exception ex)
            {
                CurrentState = CustomerServiceState.Stoped;
                _log.ErrorFormat($"调度程序启动失败！{ex.Message}");
                return false;
            }
        }

        public override bool Stop()
        {
            try
            {
                CurrentState = CustomerServiceState.Stoped;
                if (WaitJobsComplete)
                    _log.Debug("等待所有调度作业完成……");
                _scheduler.Shutdown(WaitJobsComplete);
                return _scheduler == null || _scheduler.IsShutdown;
            }
            catch (Exception ex)
            {
                CurrentState = CustomerServiceState.Stoping;
                _log.ErrorFormat("调度程序关闭失败！{0}\r\n\r\n", ex.Message);
                return false;
            }
        }

        #endregion
    }
}